package com.pianzhu.blockchainemr.service.impl;

import com.aliyun.oss.internal.OSSOperation;
import com.pianzhu.blockchainemr.mapper.UserInfoMapper;
import com.pianzhu.blockchainemr.service.UserInfoService;
import com.pianzhu.blockchainemr.utils.AliyunOSSOperator;
import com.pianzhu.blockchainemr.utils.CurrentHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @Transactional
    @Override
    public Boolean changePassword(String username, String newPassword) {
        userInfoMapper.changePassword(username, newPassword);
        String now = userInfoMapper.getCurrentPassword();
        if (now.equals(newPassword)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    @Transactional
    public Boolean uploadImg(MultipartFile file) {
        //1. 上传图片到OSS
        //2. 删除原先的图片
        //3. 保存图片信息到数据库
        String oldUrl = userInfoMapper.getCurrImgUrl();
        try {
            aliyunOSSOperator.delete(oldUrl);
            String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
            String username = new CurrentHolder().getCurrentLocal().getUsername();
            userInfoMapper.updateImgUrl(url, username);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean changeImg(String url) {

        String username = new CurrentHolder().getCurrentLocal().getUsername();
        String oldUrl = userInfoMapper.getCurrImgUrl();
        if (oldUrl != null && !oldUrl.equals(url)) {
            try {
                aliyunOSSOperator.delete(oldUrl);
                userInfoMapper.updateImgUrl(url,username);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
